package com.team.book.web;

import com.team.book.common.domain.Page;
import com.team.book.common.domain.ResponseEntity;
import com.team.book.common.exception.UncheckedException;
import com.team.book.domain.Book;
import com.team.book.domain.BorrowedRecord;
import com.team.book.domain.User;
import com.team.book.service.BookService;
import com.team.book.service.UserService;
import com.team.book.web.dto.BorrowedRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 图书
 *
 * @author Joann
 */
@RestController
@RequestMapping(value = "/api/")
public class UserController {

    @Autowired
    public UserService userService;

    @GetMapping(value = "/user")
    public ResponseEntity<Page<User>> query(Page<User> page, User user) {
        Page<User> recordPage = userService.query(page, user);
        return ResponseEntity.ok(recordPage);
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> save(@RequestBody @Valid User user) {
        try {
            int num = userService.save(user);
            if (num > 0) {
                return ResponseEntity.ok();
            }
        } catch (UncheckedException e) {
            return ResponseEntity.set(e.getStatus());
        }
        return ResponseEntity.fail();
    }

    @RequestMapping(value = "/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> update(@RequestBody User user) {
        int num = userService.update(user);
        if (num > 0) {
            return ResponseEntity.ok();
        }
        return ResponseEntity.fail();
    }

    @RequestMapping(value = "/user/pwd", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> updatePwd(@RequestBody User user) {
        try {
            userService.updatePwd(user);
            return ResponseEntity.ok();
        } catch (UncheckedException e) {
            return ResponseEntity.set(e.getStatus());
        }
    }

}
